package com.ccc.ka.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程池
 * 异步方法失效情况
 * 1、static修饰
 * 2、异步类无法被spring扫描，无注解
 * 3、异步类不可new，注解注入
 * 4、启动类enableasync
 * 5、异步方法注解transactional无效，调用异步方法的方法注解有效
 * 6、异步方法和调用异步方法的方法不能在同一个类中
 * 7、异步方法不能有返回值
 */
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
    private static final int corePoolSize = 10;
    private static final int maxPoolSize = 100;
    private static final int keepAliveTime = 10;
    private static final int queueCapacity = 200;   //缓冲队列
    private static final String threadNamePrefix = "Async-Service-";

    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor getThreadPoolTaskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        //线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
